﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace MoneyWentWhere.DataModel.Binding
{
    public class CurrencyList : BindingList<Currency>
    {
        Dictionary<String, Currency> _dict = new Dictionary<string, Currency>();

        public CurrencyList () : base() { }
        public CurrencyList(IList<Currency> list) : base(list) 
        {
            foreach(Currency c in list)
            {
                _dict.Add(c._id, c);
            }
        }

        protected override void InsertItem(int index, Currency item)
        {
            // Silently failing is fine
            if (_dict.ContainsKey(item._id)) { return; }

            _dict.Add(item._id, item);
            base.InsertItem(index, item);
        }

        protected override void ClearItems()
        {
            _dict.Clear();
            base.ClearItems();
        }

        protected override void RemoveItem(int index)
        {
            _dict.Remove(this[index]._id);
            base.RemoveItem(index);
        }

        protected override void SetItem(int index, Currency item)
        {
            // Can't silently fail, since an item is being removed as well
            if (_dict.ContainsKey(item._id)) 
            { 
                throw new ArgumentException("Item already present: " + item); 
            }

            RemoveItem(index);
            InsertItem(index, item);
        }

        public Currency this[String id]
        {
            get 
            {
                Currency c = null;
                _dict.TryGetValue(id, out c);
                return c;
            }
        }
    }
}
